$(function () {
    $("#jqGrid").jqGrid({
        url: '/platform/manage/partner/list',
        datatype: "json",
        colModel: [
            { label: '合作商编号', name: 'partnerId', index: 'partnerId', width: 50, key: true },
            { label: '身份', name: 'identity', index: 'identity', width: 80 },
            { label: '姓名', name: 'partnerName', index: 'partnerName', width: 80 },
            { label: '公司', name: 'company', index: 'company', width: 80 },
            { label: '省份地址', name: 'address', index: 'address', width: 80 },
            { label: '编号', name: 'number', index: 'number', width: 80 },
            { label: '有效期', name: 'expiryDate', index: 'expiryDate', width: 80 }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "result.list",
            page: "result.currPage",
            total: "result.totalPage",
            records: "result.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    $("#pageSizeValue").blur(function () {
        var pageSize = parseInt($(this).val());
        if (pageSize > 0){
            vm.uploadListPage.pageSize = $(this).val();
            vm.uploadListToPage();
        }
    });

});

function checkAll() {
    var check = document.getElementById("checkAll");
    var ths = document.getElementsByClassName("listContent");
    for (var i = 0;i < ths.length;i++){
        ths[i].children[0].children[0].checked = check.checked;
        if (check.checked)
            ths[i].className = "listContent warning";
        else
            ths[i].className = "listContent";
    }
}

function thClicked(e) {
    var checkBox = e.children[0].children[0];
    checkBox.checked = !checkBox.checked;
    if (checkBox.checked)
        e.className = "listContent warning";
    else
        e.className = "listContent";
}

function getAllObject() {
    var listContent = document.getElementsByClassName("listContent");
    var array = new Array();
    for (var i = 0; i < listContent.length; i++) {
        var sub = listContent[i].children;
        var checked = sub[0].children[0]
        vm.selectPartners = [];
        if (checked.checked) {
            var partnerName = sub[2].innerText;
            var identity = sub[3].innerText
            var idCard = sub[4].innerText;
            var company = sub[5].innerText;
            var address = sub[6].innerText;
            var partnerId = null;
            var number = sub[7].innerText;
            var expiryDate = sub[8].innerText;
            var typedStr = identity.substr(identity.length - 3, identity.length);
            var typed = 0;
            if (typedStr == "运营商") {
                typed = 1;
            } else if (typedStr == "创始人") {
                typed = 0;
            } else {
                typed = 2;
            }
            var json = {
                "partnerId":partnerId,
                "typed": typed,
                "partnerName": partnerName,
                "identity": identity,
                "idCard": idCard,
                "company": company,
                "address": address,
                "number": number,
                "expiryDate": expiryDate
            };
            array.push(json);
        }
    }
    return array;
}

var vm = new Vue({
    el:'#rrapp',
    data:{
        options: [
            { text: '爱卡卡创业版创始人', value: 0 },
            { text: '爱卡卡创业版运营商', value: 1 },
            { text: '爱卡卡品牌运营中心', value: 2 }
        ],
        q:{
            partnerName: null
        },
        showList: true,
        showUpload:false,
        showUploadList:false,
        showAdd:false,
        title: null,
        partnerExcel:{},
        uploadListPage:{
            currentPage:1,
            pageSize:50,
            pageCount:1,
            pageData:[]
        },
        partner:{}

    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.showAdd = true;
            vm.showUploadList = false;
            vm.showUpload = false;
            vm.title = "新增";
            vm.partner = {};
            vm.partner.typed = 0;
        },
        addBatch: function () {
            vm.showList = false;
            vm.showAdd = false;
            vm.showUpload = true;
            vm.showUploadList = false;
            vm.title = "批量添加";
            vm.partner = {};
            vm.partner.typed = 0;
        },
        update: function (event) {
            var partnerId = getSelectedRow();
            if(partnerId == null){
                return ;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.showAdd =true;

            vm.getInfo(partnerId)
        },
        checkAll:function (e) {
           checkAll();
        },
        saveAll:function (e) {
            // alert(getAllObject().length)
            var arr = getAllObject();
            if (arr.length < 1){
                alert("请选择要添加的内容");
                return;
            }
            $.ajax({
                url: "/platform/manage/partner/saveAll",
                type: "POST",
                data: JSON.stringify(arr),
                success: function(r){
                    if(r.code == 200){
                        alert('操作成功', function(index){
                        });
                        for (var i = arr.length-1;i>=0;i--){
                            vm.partnerExcel.splice(arr[i].partnerId - 1,1);
                        }
                        vm.showUploadList = false;
                        vm.uploadListToPage();
                    }else{
                        alert(r.message);
                    }
                }
            });
        },
        uploadExcel: function (e) {
            $.ajaxFileUpload({
                url : '/platform/manage/partner/uploadExcel',
                type:"POST",
                secureuri : false,
                fileElementId : ['fileToUpload'],
                dataType : 'json',
                contentType:'multipart/form-data',
                success : function(data, status) {
                    // vm.showUploadList = true;
                    vm.partnerExcel = data.result;
                    // this.uploadListToPage()
                    vm.uploadListToPage()
                },
                error : function(data, status, e) {
                    var msg = data.responseText;
                    console.log(data);
                    var str = msg.substr(msg.indexOf("{"),msg.lastIndexOf("}") - msg.indexOf("{") + 1)
                    var json = JSON.parse(str);
                    alert(json.msg);
                    // document.getElementById("uploadError").innerHTML = data.responseText;
                    // alert('上传出错:'+data.data);
                }
            })
        },
        uploadPrePage:function () {
            if (vm.uploadListPage.currentPage > 1){
                vm.uploadListPage.currentPage--;
            }
            if (vm.uploadListPage.currentPage <= 1){
                //disabled
                document.getElementById("pagePre").className = "previous disabled";
            }
            document.getElementById("pageNext").className = "next";
            vm.uploadListToPage()
        },
        uploadNextPage:function () {
            if (vm.uploadListPage.currentPage < vm.uploadListPage.pageCount){
                vm.uploadListPage.currentPage++;
            }
            if (vm.uploadListPage.currentPage >= vm.uploadListPage.pageCount){
                //disabled
                document.getElementById("pageNext").className = "next disabled";
            }
            document.getElementById("pagePre").className = "previous";
            vm.uploadListToPage()
        },
        uploadListToPage:function () {
            vm.uploadListPage.pageData.splice(0,vm.uploadListPage.pageData.length);
            if (vm.partnerExcel.length % vm.uploadListPage.pageSize == 0){
                vm.uploadListPage.pageCount = vm.partnerExcel.length / vm.uploadListPage.pageSize;
            }else {
                vm.uploadListPage.pageCount = parseInt(vm.partnerExcel.length / vm.uploadListPage.pageSize) + 1;
            }
            if (vm.uploadListPage.currentPage * vm.uploadListPage.pageSize < vm.partnerExcel.length){
                for (var i = (vm.uploadListPage.currentPage-1) * vm.uploadListPage.pageSize;i < vm.uploadListPage.pageSize * vm.uploadListPage.currentPage;i++){
                    vm.partnerExcel[i].partnerId = i + 1;
                    vm.uploadListPage.pageData.push(vm.partnerExcel[i])
                }
            }else {
                for (var i = (vm.uploadListPage.currentPage-1) * vm.uploadListPage.pageSize;i < vm.partnerExcel.length;i++){
                    vm.partnerExcel[i].partnerId = i + 1;
                    vm.uploadListPage.pageData.push(vm.partnerExcel[i])
                }
            }
            vm.showUploadList = true;
            var check = document.getElementById("checkAll");
            check.checked = false;
            checkAll();
        },
        saveOrUpdate: function (event) {
            var url = vm.partner.partnerId == null ? "/platform/manage/partner/save" : "/platform/manage/partner/update";
            console.log(url);
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(vm.partner),
                success: function(r){
                    if(r.code == 200){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.message);
                    }
                }
            });
        },
        del: function (event) {
            var partnerIds = getSelectedRows();
            if(partnerIds == null){
                return ;
            }

            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: "/platform/manage/partner/delete",
                    data: JSON.stringify(partnerIds),
                    success: function(r){
                        if(r.code == 200){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.message);
                        }
                    }
                });
            });
        },
        getInfo: function(partnerId){
            $.get("/platform/manage/partner/info/"+partnerId, function(r){
                vm.partner = r.result;
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.showUpload = false;
            vm.showUploadList = false;
            vm.showAdd = false;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'partnerName': vm.q.partnerName},
                page:page,
            }).trigger("reloadGrid");
        }
    }
});